import { Button } from "element-ui";
import slotsVnode from "@/components/mixins/slotsVnode";
// import { mapGetters } from "vuex";
/*
 * cButton
 * loading 若click为Promise则自动为按钮添加loading
 * size 默认为small
 *  */
export default {
  name: "cButton",
  props: {
    ...Button.props,
    size: {
      type: String,
      default: "small",
    },
    hasPermi: {
      // 使用方式跟v-hasPermi 一致
      type: Array,
      default: () => [],
    },
    isShow: {
      // 类型v-if
      default: true,
    },
    showLoading: {
      // false:若点击事件返回promise按钮也不会加上loading
      type: Boolean,
      default: true,
    },
  },
  mixins: [slotsVnode],
  computed: {
    // ...mapGetters(["permissions"]),
  },
  data() {
    return {
      isRender: true, // 按钮的权限
      btnLoading: this.loading,
    };
  },

  watch: {
    loading: {
      handler(value) {
        this.btnLoading = value;
      },
    },
  },
  created() {
    this.verifyPermi();
  },
  methods: {
    verifyPermi() {
      this.isRender = true;
      const value = this.hasPermi;
      const all_permission = "*:*:*";
      const permissions = this.permissions; // 先调用的getInfo,再调的router时,所以不需要watch

      if (value && value instanceof Array && value.length > 0) {
        const permissionFlag = value;

        const hasPermissions = permissions.some((permission) => {
          return (
            all_permission === permission || permissionFlag.includes(permission)
          );
        });
        if (!hasPermissions) {
          this.isRender = false;
        }
      }
    },
    async dispatch(res) {
      if (!this.showLoading) return;
      if (res instanceof Promise) {
        // 如果为Promise
        try {
          this.btnLoading = true;
          await res;
          this.btnLoading = false;
        } catch (e) {
          console.error(e);
          this.btnLoading = false;
        }
      }
    },
    handleClick(e) {
      if (!this.$listeners.click) {
        return;
      }
      this.dispatch(this.$listeners.click(e));
    },
  },
  render() {
    if (!this.isShow) return;
    return this.isRender ? (
      <Button
        ref="elButton"
        {...{
          props: {
            ...this.$props,
            loading: this.btnLoading,
          },
          attrs: {
            ...this.$attrs,
          },
          on: {
            ...this.$listeners,
            click: this.handleClick,
          },
        }}
      >
        {this.slotsVnode()}
      </Button>
    ) : null;
  },
};
